//
//  NSDate+Extension.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/30.
//  Copyright © 2016年 Coco. All rights reserved.
//

import Foundation

extension NSDate {
    /// 将新浪返回的数据转成NSDate
    class func dateFromSinaString(dateString: String) -> NSDate {
        
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        formatter.locale = NSLocale(localeIdentifier: "EN")
        let date = formatter.dateFromString(dateString) ?? NSDate()
//        CNPrint(item: "dateFromSinaString: \(date)")
        return date
    }
    /// 将NSDate转成可供显示的字符串
    func sinaDisplayString() -> String {
        
        let formatter = NSDateFormatter()
        
        formatter.locale = NSLocale(localeIdentifier: "EN")
        
        let calendar = NSCalendar.currentCalendar()
        
        if calendar.isDateInToday(self) {
            
            let interval = Int(NSDate().timeIntervalSinceDate(self))
            if interval < 60 {
                return "刚刚"
            } else if interval < 60 * 60 {
                return "\(interval / 60)分钟前"
            } else {
                return "\(interval / 3600)小时前"
            }
        } else if calendar.isDateInYesterday(self) {
            
            formatter.dateFormat = "昨天 HH:mm"
            return formatter.stringFromDate(self)
            
        } else {
            
            let result = calendar.compareDate(NSDate(), toDate: self, toUnitGranularity: NSCalendarUnit.Year)
            if result == NSComparisonResult.OrderedSame {
                formatter.dateFormat = "MM-dd HH:mm"
                return formatter.stringFromDate(self)
            } else {
                formatter.dateFormat = "yyyy-MM-dd HH:mm"
                return formatter.stringFromDate(self)
            }
        }
        
    }
}